package com.approval.controller;

import com.approval.dto.ProcessValidationRequest;
import com.approval.dto.ProcessValidationResult;
import com.approval.dto.Result;
import com.approval.entity.ApprovalProcess;
import com.approval.service.ApprovalProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程控制器
 */
@RestController
@RequestMapping("/processes")
public class ProcessController {

    @Autowired
    private ApprovalProcessService processService;

    @GetMapping
    public Result<List<Map<String, Object>>> getAllProcesses() {
        // 流程管理接口，显示所有流程，不进行发起人权限过滤
        List<ApprovalProcess> processes = processService.getAllProcesses();
        List<Map<String, Object>> processMaps = processes.stream()
            .map(process -> processService.convertProcessToMap(process))
            .collect(java.util.stream.Collectors.toList());
        return Result.success(processMaps);
    }

    @GetMapping("/active")
    public Result<List<ApprovalProcess>> getActiveProcesses() {
        List<ApprovalProcess> processes = processService.getActiveProcesses();
        return Result.success(processes);
    }

    /**
     * 获取用户可发起的流程列表（根据发起人权限过滤）
     */
    @GetMapping("/user/startable")
    public Result<List<Map<String, Object>>> getStartableProcesses() {
        List<Map<String, Object>> processesWithPermission = processService.getAllProcessesWithPermission();
        return Result.success(processesWithPermission);
    }

    @GetMapping("/{id}")
    public Result<ApprovalProcess> getProcessById(@PathVariable Long id) {
        ApprovalProcess process = processService.getProcessById(id);
        return Result.success(process);
    }

    @PostMapping
    public Result<ApprovalProcess> createProcess(@Valid @RequestBody ApprovalProcess process) {
        ApprovalProcess created = processService.createProcess(process);
        return Result.success(created);
    }

    @PutMapping("/{id}")
    public Result<ApprovalProcess> updateProcess(@PathVariable Long id, @Valid @RequestBody ApprovalProcess process) {
        ApprovalProcess updated = processService.updateProcess(id, process);
        return Result.success(updated);
    }

    /**
     * 更新流程（带版本管理）
     */
    @PutMapping("/{id}/update-with-version")
    public Result<ApprovalProcess> updateProcessWithVersion(@PathVariable Long id,
                                                           @Valid @RequestBody Map<String, Object> request) {
        ApprovalProcess process = new ApprovalProcess();
        process.setProcessName((String) request.get("processName"));
        process.setCategory((String) request.get("category"));
        process.setProcessXml((String) request.get("processXml"));
        process.setFormConfig((String) request.get("formConfig"));
        process.setProcessConfig((String) request.get("processConfig"));
        process.setDescription((String) request.get("description"));
        process.setIcon((String) request.get("icon"));
        // 注意：processKey 会在 createNewVersion 方法中自动生成

        String updateStrategy = (String) request.getOrDefault("updateStrategy", "CREATE_NEW_VERSION");

        ApprovalProcess updated = processService.updateProcessWithVersionManagement(id, process, updateStrategy);
        return Result.success(updated);
    }

    /**
     * 检查流程是否有正在运行的实例
     */
    @GetMapping("/{id}/running-instances")
    public Result<Map<String, Object>> checkRunningInstances(@PathVariable Long id) {
        boolean hasRunningInstances = processService.hasRunningInstances(id);
        int runningInstanceCount = processService.getRunningInstanceCount(id);

        Map<String, Object> result = new HashMap<>();
        result.put("hasRunningInstances", hasRunningInstances);
        result.put("runningInstanceCount", runningInstanceCount);
        result.put("canUpdate", !hasRunningInstances);

        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteProcess(@PathVariable Long id) {
        processService.deleteProcess(id);
        return Result.success();
    }

    /**
     * 验证流程配置
     */
    @PostMapping("/validate")
    public Result<ProcessValidationResult> validateProcess(@Valid @RequestBody ProcessValidationRequest request) {
        ProcessValidationResult validationResult = processService.validateProcess(request.getProcessConfig());
        return Result.success(validationResult);
    }

    /**
     * 导入流程模板
     */
    @PostMapping("/import")
    public Result<ApprovalProcess> importProcess(@RequestBody Map<String, Object> processData) {
        ApprovalProcess importedProcess = processService.importProcess(processData);
        return Result.success(importedProcess);
    }

    /**
     * 导出流程模板
     */
    @GetMapping("/{id}/export")
    public Result<Map<String, Object>> exportProcess(@PathVariable Long id) {
        Map<String, Object> processTemplate = processService.exportProcess(id);
        return Result.success(processTemplate);
    }

    /**
     * 获取流程模板列表
     */
    @GetMapping("/templates")
    public Result<List<ApprovalProcess>> getProcessTemplates() {
        List<ApprovalProcess> templates = processService.getProcessTemplates();
        return Result.success(templates);
    }

    /**
     * 保存为模板
     */
    @PostMapping("/{id}/save-as-template")
    public Result<ApprovalProcess> saveAsTemplate(@PathVariable Long id, @RequestBody Map<String, Object> templateData) {
        ApprovalProcess template = processService.saveAsTemplate(id, templateData);
        return Result.success(template);
    }

    /**
     * 批量删除流程
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteProcesses(@RequestBody List<Long> processIds) {
        processService.batchDeleteProcesses(processIds);
        return Result.success();
    }

    /**
     * 批量更新流程状态
     */
    @PutMapping("/batch/status")
    public Result<Void> batchUpdateStatus(@RequestBody Map<String, Object> request) {
        List<Long> processIds = (List<Long>) request.get("processIds");
        Integer status = (Integer) request.get("status");
        processService.batchUpdateStatus(processIds, status);
        return Result.success();
    }

    /**
     * 检查用户是否有权限发起指定流程
     */
    @GetMapping("/{id}/check-permission")
    public Result<Map<String, Object>> checkProcessPermission(@PathVariable Long id) {
        Map<String, Object> result = processService.checkProcessPermission(id);
        return Result.success(result);
    }

    /**
     * 获取流程的历史版本
     */
    @GetMapping("/history/{processKey}")
    public Result<List<ApprovalProcess>> getProcessHistory(@PathVariable String processKey) {
        List<ApprovalProcess> historyVersions = processService.getProcessHistoryVersions(processKey);
        return Result.success(historyVersions);
    }

    /**
     * 获取流程的最新版本
     */
    @GetMapping("/latest/{processKey}")
    public Result<ApprovalProcess> getLatestProcess(@PathVariable String processKey) {
        ApprovalProcess latestProcess = processService.getLatestProcessByKey(processKey);
        if (latestProcess == null) {
            return Result.error("流程不存在");
        }
        return Result.success(latestProcess);
    }
}
